//==============================================================================
//
//           DAtExit - the "at-exit" class in the ofc-library
//
//               Copyright (C) 2003  Dick van Oudheusden
//  
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public
// License along with this library; if not, write to the Free
// Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
//
//==============================================================================
// 
//  $Date: 2004-02-20 20:16:33 $ $Revision: 1.2 $
//
//==============================================================================

#include "ofc/DAtExit.h"

#include <stdlib.h>

#include "ofc/DList.h"


#if _INTERFACE_

#include "ofc/config.h"


// The AtExit implements a number of methods for insuring the freeing of 
// objects during the exit of the program. This class has only class methods
// (singleton).

@interface DAtExit : Object
{
}

#endif


@implementation DAtExit


#if _PRIVATE_

// the list with all the objects that must be freed

static DList *_list = nil;

//
// Do the at-exit function
// 
// @return none
// 

static void _doExit()
{
  if (_list != nil)
  {
    [_list free];
  }
}
#endif

//
// Add an object that must be freed during program exit
//
// @param obj      the object
// 
// @return none
//

+ (void) add :(id) obj
{
  if (obj != nil)
  {
    if (_list == nil)
    {
      _list = [[DList alloc] init];
      
      atexit(_doExit);
    }
  
    [_list append :obj];
  }
}

//
// Remove an object from freeing during program exit
//
// @param obj      the object
//
// @return none
//

+ (void) remove :(id) obj
{
  if ((obj != nil) && (_list != nil))
  {
    if (![_list remove :obj])
    {
      WARNING(DW_INVALID_ARG, "obj");
    }
  }
}

@end

/*==========================================================================*/
         
